﻿using System;
using System.IO;
using System.Text;
using System.Windows;
using System.Xml;
using System.Xml.Serialization;
using Microsoft.Build.Framework;
using Omu.ValueInjecter;

/*
 * Copyright (c) 2007-2012, Thomas Ardal (thomasardalatgmail.com), Lex Li (supportatlextm.com), Rami Abughazaleh (rami.abughazalehatgmail.com)
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
 *
 * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
 *
 * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
 *
 * * Neither the name of Thomas Ardal nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
namespace PerformanceDude.MSBuildShellExtension.Common
{
    [Serializable]
    public class ConfigurationSettings : DependencyObject
    {
        #region properties

        [XmlAttribute]
        public bool ShowErrors
        {
            get { return (bool)GetValue(ShowErrorsProperty); }
            set { SetValue(ShowErrorsProperty, value); }
        }
        public static readonly DependencyProperty ShowErrorsProperty = DependencyProperty.Register("ShowErrors", typeof(bool), typeof(ConfigurationSettings));

        [XmlAttribute]
        public bool ShowMessages
        {
            get { return (bool)GetValue(ShowMessagesProperty); }
            set { SetValue(ShowMessagesProperty, value); }
        }
        public static readonly DependencyProperty ShowMessagesProperty = DependencyProperty.Register("ShowMessages", typeof(bool), typeof(ConfigurationSettings));

        [XmlAttribute]
        public bool ShowWarnings
        {
            get { return (bool)GetValue(ShowWarningsProperty); }
            set { SetValue(ShowWarningsProperty, value); }
        }
        public static readonly DependencyProperty ShowWarningsProperty = DependencyProperty.Register("ShowWarnings", typeof(bool), typeof(ConfigurationSettings));

        [XmlAttribute]
        public double Height
        {
            get { return (double)GetValue(HeightProperty); }
            set { SetValue(HeightProperty, value); }
        }
        public static readonly DependencyProperty HeightProperty = DependencyProperty.Register("Height", typeof(double), typeof(ConfigurationSettings));

        [XmlAttribute]
        public double Left
        {
            get { return (double)GetValue(LeftProperty); }
            set { SetValue(LeftProperty, value); }
        }
        public static readonly DependencyProperty LeftProperty = DependencyProperty.Register("Left", typeof(double), typeof(ConfigurationSettings));

        [XmlAttribute]
        public double Top
        {
            get { return (double)GetValue(TopProperty); }
            set { SetValue(TopProperty, value); }
        }
        public static readonly DependencyProperty TopProperty = DependencyProperty.Register("Top", typeof(double), typeof(ConfigurationSettings));

        [XmlAttribute]
        public bool Topmost
        {
            get { return (bool)GetValue(TopmostProperty); }
            set { SetValue(TopmostProperty, value); }
        }
        public static readonly DependencyProperty TopmostProperty = DependencyProperty.Register("Topmost", typeof(bool), typeof(ConfigurationSettings));

        [XmlAttribute]
        public double Width
        {
            get { return (double)GetValue(WidthProperty); }
            set { SetValue(WidthProperty, value); }
        }
        public static readonly DependencyProperty WidthProperty = DependencyProperty.Register("Width", typeof(double), typeof(ConfigurationSettings));

        [XmlAttribute]
        public WindowState WindowState
        {
            get { return (WindowState)GetValue(WindowStateProperty); }
            set { SetValue(WindowStateProperty, value); }
        }
        public static readonly DependencyProperty WindowStateProperty = DependencyProperty.Register("WindowState", typeof(WindowState), typeof(ConfigurationSettings));

        [XmlAttribute]
        public WindowStartupLocation WindowStartupLocation
        {
            get { return (WindowStartupLocation)GetValue(WindowStartupLocationProperty); }
            set { SetValue(WindowStartupLocationProperty, value); }
        }
        public static readonly DependencyProperty WindowStartupLocationProperty = DependencyProperty.Register("WindowStartupLocation", typeof(WindowStartupLocation), typeof(ConfigurationSettings));

        [XmlAttribute]
        public bool SaveWindowLocation
        {
            get { return (bool)GetValue(SaveWindowLocationProperty); }
            set { SetValue(SaveWindowLocationProperty, value); }
        }
        public static readonly DependencyProperty SaveWindowLocationProperty = DependencyProperty.Register("SaveWindowLocation", typeof(bool), typeof(ConfigurationSettings));

        [XmlAttribute]
        public bool ShowOutputWindow
        {
            get { return (bool)GetValue(ShowOutputWindowProperty); }
            set { SetValue(ShowOutputWindowProperty, value); }
        }
        public static readonly DependencyProperty ShowOutputWindowProperty = DependencyProperty.Register("ShowOutputWindow", typeof(bool), typeof(ConfigurationSettings));

        [XmlAttribute]
        public bool ShowOutputWindowOnlyIfBuildFails
        {
            get { return (bool)GetValue(ShowOutputWindowOnlyIfBuildFailsProperty); }
            set { SetValue(ShowOutputWindowOnlyIfBuildFailsProperty, value); }
        }
        public static readonly DependencyProperty ShowOutputWindowOnlyIfBuildFailsProperty = DependencyProperty.Register("ShowOutputWindowOnlyIfBuildFails", typeof(bool), typeof(ConfigurationSettings));

        [XmlAttribute]
        public bool CloseWindowsOnSuccessfulBuild
        {
            get { return (bool)GetValue(CloseWindowsOnSuccessfulBuildProperty); }
            set { SetValue(CloseWindowsOnSuccessfulBuildProperty, value); }
        }
        public static readonly DependencyProperty CloseWindowsOnSuccessfulBuildProperty = DependencyProperty.Register("CloseWindowsOnSuccessfulBuild", typeof(bool), typeof(ConfigurationSettings));

        [XmlAttribute]
        public bool FlashWindowWhenFinished
        {
            get { return (bool)GetValue(FlashWindowWhenFinishedProperty); }
            set { SetValue(FlashWindowWhenFinishedProperty, value); }
        }
        public static readonly DependencyProperty FlashWindowWhenFinishedProperty = DependencyProperty.Register("FlashWindowWhenFinished", typeof(bool), typeof(ConfigurationSettings));

        [XmlAttribute]
        public LoggerVerbosity LoggingVerbosity
        {
            get { return (LoggerVerbosity)GetValue(LoggingVerbosityProperty); }
            set { SetValue(LoggingVerbosityProperty, value); }
        }
        public static readonly DependencyProperty LoggingVerbosityProperty = DependencyProperty.Register("LoggingVerbosity", typeof(LoggerVerbosity), typeof(ConfigurationSettings));
        
        [XmlAttribute]
        public bool MaxCpuCount
        {
            get { return (bool)GetValue(MaxCpuCountProperty); }
            set { SetValue(MaxCpuCountProperty, value); }
        }
        public static readonly DependencyProperty MaxCpuCountProperty = DependencyProperty.Register("MaxCpuCount", typeof(bool), typeof(ConfigurationSettings));

        #endregion

        private string ConfigurationFilePath;

        /// <summary>
        /// Initializes a new instance of the <see cref="ConfigurationSettings"/> class.
        /// A parameter-less constructor is required for xml serialization.
        /// </summary>
        public ConfigurationSettings()
            : this(false)
        {
            
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="ConfigurationSettings"/> class.
        /// </summary>
        /// <param name="loadConfigurationFile">if set to <c>true</c> [load configuration file].</param>
        public ConfigurationSettings(bool loadConfigurationFile)
        {
            try
            {
                this.ShowErrors = true;
                this.ShowWarnings = false;
                this.ShowMessages = false;
                this.Height = 300;
                this.Width = 600;
                this.Top = 0;
                this.Left = 0;
                this.Topmost = false;
                this.WindowState = WindowState.Normal;
                this.WindowStartupLocation = WindowStartupLocation.CenterScreen;
                this.ShowOutputWindow = true;
                this.ShowOutputWindowOnlyIfBuildFails = false;
                this.CloseWindowsOnSuccessfulBuild = true;
                this.FlashWindowWhenFinished = true;
                this.LoggingVerbosity = LoggerVerbosity.Minimal;
                this.SaveWindowLocation = false;
                this.MaxCpuCount = true;

                if (loadConfigurationFile)
                {
                    ConfigurationFilePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
                        @"PerformanceDude\MSBuildShellExtension\MSBuildShellExtension.config");

                    XmlSerializer xmlSerializer = new XmlSerializer(typeof(ConfigurationSettings));

                    bool fileExists = File.Exists(ConfigurationFilePath);
                    if (fileExists)
                    {
                        using (FileStream fileStream = new FileStream(ConfigurationFilePath, FileMode.Open, FileAccess.Read))
                        {
                            ConfigurationSettings settings = (ConfigurationSettings)xmlSerializer.Deserialize(fileStream);

                            this.InjectFrom(settings);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ExceptionHandler.Log(ex);
                throw;
            }
        }

        public void Save()
        {
            try
            {
                XmlSerializer xmlSerializer = new XmlSerializer(typeof(ConfigurationSettings));

                XmlSerializerNamespaces xmlSerializerNamespaces = new XmlSerializerNamespaces();
                xmlSerializerNamespaces.Add("", "");

                XmlWriterSettings xmlWriterSettings = new XmlWriterSettings()
                {
                    Encoding = Encoding.UTF8,
                    OmitXmlDeclaration = true
                };

                using (XmlWriter writer = XmlWriter.Create(ConfigurationFilePath, xmlWriterSettings))
                {
                    xmlSerializer.Serialize(writer, this, xmlSerializerNamespaces);
                }
            }
            catch (Exception ex)
            {
                ExceptionHandler.Log(ex);
                throw;
            }
        }
    }
}
